import { Dep } from "./dep.js"
import { observer } from "./obsever.js"
// import { watchers } from "./watcher.js"

export const defineReactive = function (obj, key, val) {
  if (typeof obj[key] == 'object') {
    observer(obj[key])
  }
  // 注意这个 dep 对应的 这个 obj 的key 
  const dep = new Dep()
  Object.defineProperty(obj, key, {
    get() {
      // 通过 Dep 收集watch 依赖
      Dep.target && dep.addDep(Dep.target)
      return val
    },
    set(newVal) {
      if (newVal !== val) {
        // console.log('set', newVal, val);
        // watchers.forEach(watcher => {
        //   watcher.update()
        // })
        dep.notify()
        val = newVal
      }
    }
  })
}

export const proxy = function (vm, sourceKey) {
  Object.keys(vm[sourceKey]).forEach(key => {
    Object.defineProperty(vm, key, {
      get() {
        return vm[sourceKey][key]
      },
      set(newVal) {
        vm[sourceKey][key] = newVal
      }
    })
  })
}